<template>
  <DialogCard :title="title" :width="width" :height="height" @close="close">
    <template v-slot:content>
      <div class="content">
        <!-- <div class="flex-content">
          <div class="flex-title">选择设备</div>
          <div class="select-eqiupment">
            <div class="select-item">
              <span>卫正大厦</span>
              <el-icon class="close-icon"><Close /></el-icon>
            </div>
          </div>
        </div> -->
        <div class="flex-content">
          <div class="flex-title">范围编辑</div>
          <div class="map-edit">
            <div class="btn-list">
              <div class="btn-left">
                <el-button @click="clickBtn(1)" v-if="clickIndex == 0">绘制</el-button>
                <el-button @click="clickBtn(2)" v-if="clickIndex == 0">编辑</el-button>
                <el-button @click="clickBtn(3)" v-if="clickIndex == 0">删除</el-button>
                <template v-if="clickIndex !== 0">
                  <span class="draw-title" v-if="clickIndex == 1">
                    {{
                      defensArr.length == 0
                        ? '核心圈'
                        : defensArr.length == 1
                        ? '反制圈'
                        : '警戒圈'
                    }}绘制:
                  </span>
                  <el-button v-if="clickIndex == 1 && drawType == 0" @click="onDrawType(1)"
                    >手动绘制</el-button
                  >
                  <el-button v-if="clickIndex == 1 && drawType == 0" @click="onDrawType(2)"
                    >自动绘制</el-button
                  >
                  <el-button
                    v-if="clickIndex == 1 && drawType == 1 && shapeType !== 'circle'"
                    :type="shapeType == 'polygon' ? 'primary' : ''"
                    @click="selectShape('polygon')"
                    >绘制多边形</el-button
                  >
                  <el-button
                    v-if="clickIndex == 1 && drawType == 1 && shapeType !== 'polygon'"
                    :type="shapeType == 'circle' ? 'primary' : ''"
                    @click="selectShape('circle')"
                    >绘制圆形</el-button
                  >
                  <span v-if="clickIndex == 1 && drawType == 2">
                    <span class="radius-txt">半径(单位:米)：</span>
                    <el-input
                      class="radius-input"
                      v-model="radiusVal"
                      style="color: black; width: 240px"
                      placeholder="请输入半径"
                      @change="changeRadius" />
                  </span>
                  <el-button
                    v-if="clickIndex == 1 && drawType !== 0 && shapeType !== ''"
                    text
                    @click="selectShape('')"
                    >结束绘制</el-button
                  >
                  <el-button @click="closeDraw(clickIndex)" v-if="drawType == 0">
                    退出
                    <span v-if="clickIndex == 1">绘制</span>
                    <span v-if="clickIndex == 2">编辑</span>
                    <span v-if="clickIndex == 3">删除</span>
                    模式
                  </el-button>
                  <el-tooltip v-if="clickIndex > 0" :content="toolText" raw-content placement="top-start" effect="light">
                    <el-button type="text"
                      ><el-icon><QuestionFilled /></el-icon>操作提示</el-button
                    >
                  </el-tooltip>
                </template>
              </div>
              <div class="btn-right">
                <el-button @click="changeLayer" :type="vectorShow ? '' : 'primary'"
                  >卫星地图</el-button
                >
                <!-- <el-button plain type="primary">显示设备</el-button> -->
                <!-- <el-select
                  v-model="placeVal"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入内容"
                  :remote-method="remoteMethod"
                  :loading="loading"
                  style="width: 240px; margin-left: 10px">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value" />
                </el-select> -->
              </div>
            </div>
            <div id="coverageMap"></div>
          </div>
        </div>
        <div class="btn-box">
          <div class="content-btn" @click="onConfirm">确认</div>
        </div>
      </div>
    </template>
  </DialogCard>
</template>

<script setup>
  import { ref, onMounted, toRefs, inject, onUnmounted } from 'vue'
  import DialogCard from '@/components/home/dialog/dialogCard.vue'
  import editPolyGonFunC from '@/utils/editPolygon.js'
  import editCircleFunC from '@/utils/editCircle.js'
  import { createDefense, editDefense, delDefense, getDefense } from '@/api/defens.js'
  const props = defineProps({ title: 'string', width: Number, height: Number })
  const { title, width, height } = toRefs(props)

  const emit = defineEmits(['closeDialog', 'getDenfensInfo', 'enableTool'])
  const vectorShow = ref(true)
  const placeVal = ref('')
  const radiusVal = ref('')
  const loading = ref(false)
  const list = ref([])
  const clickIndex = ref(0)
  const drawType = ref(0) //防御圈的绘制类型
  const shapeType = ref('') //防御圈绘制的形状
  const editShape = ref(false) //是否编辑多边形
  const deleteShape = ref(false) //是否删除多边形
  const message = inject('$message')
  const toolText = ref(null)
  /**
   * @description: 关闭弹窗
   */
  const close = () => {
    destroyCesiumViewer()
    emit('closeDialog', 'defense')
  }
  /**
   * @description: 销毁cesium
   */
  const destroyCesiumViewer = () => {
    if (Cesium.defined(viewer)) {
      viewer.entities.removeAll()
      viewer.imageryLayers.removeAll()
      viewer.dataSources.removeAll()
      // viewer.scene.primitives.removeAll();
      // 获取webgl上下文
      let gl = viewer.scene.context._originalGLContext
      gl.canvas.width = 1
      gl.canvas.height = 1
      viewer.destroy() // 销毁Viewer实例
      gl.getExtension('WEBGL_lose_context').loseContext()
      gl = null
      window.viewer = null
      var cesiumContainer = document.getElementById('coverageMap')
      if (cesiumContainer) {
        cesiumContainer.remove() // 移除与地图相关的DOM元素
      }
      console.log('cesium销毁')

      // 清理其他JavaScript对象和事件监听器
      // ...
    }
  }
  /**
   * @description: 初始化地图
   */
  let viewer = null
  // 是否形成面
  let isDrawPolyGon = false
  let polyGonShow = false
  // 是否开始画多边形
  let isDrawLine = false
  // 画面点位数据
  let pointArr = []
  // 当前点位的数据
  let nowPoint = []
  let pointAndLineEntity = {
    pointEntityArr: [],
    lineEntityArr: [],
    demoLineEntityArr: [],
    polygonEntityArr: [],
    addPolygonEntity: [],
  }
  let updatePoints = [] //鼠标移动更新后的点坐标
  let centerPoint = []
  let circleEntity = {
    circlePonit: [], //圆心
    circleEntityArr: [], //圆形防御圈
    circleDragPonit: [], //圆边缘拖动的点
  }
  let circleRadius = 1000
  let dragCircle = false //对圆形半径进行拖拽
  let dragCircleCenter = false //对圆新进行拖拽
  let selectCircleIndex = null //选中圆形的Index
  let defensArr = []
  let defensColorMap = new Map()
  defensColorMap.set(10, '#4d90fe') //警戒圈-蓝色
  defensColorMap.set(5, '#ffaa00') //反制圈-黄色
  defensColorMap.set(1, '#ff0000') //核心圈-红色
  // 当前选择的编辑点
  let nowEditPoint = []
  const initMap = () => {
    viewer = new Cesium.Viewer('coverageMap', {
      homeButton: false,
      sceneModePicker: false,
      baseLayerPicker: false, // 影像切换
      animation: false, // 是否显示动画控件
      infoBox: false, // 是否显示点击要素之后显示的信息
      selectionIndicator: false, // 要素选中框
      geocoder: false, // 是否显示地名查找控件
      timeline: false, // 必须为true显示时间线组件（如不想显示可以使用样式层叠表修改display：none） 否则viewer.timeline.zoomTo会报undefined错误
      fullscreenButton: false,
      navigationHelpButton: false, // 是否显示帮助信息控件
      shouldAnimate: true, // 必须为true开启动画 否则不会达到飞机模型飞行动画效果
    })
    window.viewer = viewer
    viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString('rgba(49, 108, 140, 0.1)') //设置地球颜色
    viewer.scene.skyAtmosphere.show = false // 隐藏大气，不隐藏的话周围会有一圈光晕
    viewer._cesiumWidget._creditContainer.style.display = 'none' // 去除logo
    viewer.imageryLayers.removeAll(true) // 移除所有图层并销毁

    //禁用cesium左键的双击事件
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
      Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
    )

    // 初始化加载海宁矢量地图
    changBaseMap('haiNingVector')

    if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
      //判断是否支持图像渲染像素化处理
      viewer.resolutionScale = window.devicePixelRatio
    }
    //是否开启抗锯齿
    viewer.scene.fxaa = true
    viewer.scene.postProcessStages.fxaa.enabled = true

    //限制缩放的最大高度
    viewer.scene.screenSpaceCameraController.maximumZoomDistance = 100000
    // 声明监听事件
    let handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas)

    // 监听鼠标左击事件
    handler.setInputAction((event) => {
      let pick = viewer.scene.pick(event.position)
      let defensLen = defensArr.length
      // 判断是否有实体，有实体点击多边形显示编辑点
      if (pick && pick.id && pick.id.polygon) {
        pointAndLineEntity.addPolygonEntity.map((item, index) => {
          // 点击多边形编辑点
          if (pick.id._id == item._id) {
            // 编辑多边形
            if (editShape.value) {
              editVisible.value = true
              // 实体存在生成编辑点
              editPolyGonFunC.delDemoEntity(pointAndLineEntity.pointEntityArr)
              pointAndLineEntity.pointEntityArr = []
              for (let cartesian of pick.id.polygon.hierarchy._value.positions) {
                const point = editPolyGonFunC.drawEditPoint(cartesian)
                // 保存点的ID以便删除
                pointAndLineEntity.pointEntityArr.push(point)
              }
              pointAndLineEntity.polygonEntityArr.push(pick)
              circleVisible(false) //隐藏圆形的圆心和拖拽点
            }
            //删除多边形
            if (deleteShape.value) {
              deleteDenfenData()
              // viewer.entities.remove(item)
              // pointAndLineEntity.addPolygonEntity.splice(index, 1)
              // defensArr.map((item, index) => {
              //   if (item.id == pick.id._id) {
              //     defensArr.splice(index, 1)
              //   }
              // })
            }
          }
        })
      } else {
        if (shapeType.value == 'polygon') {
          // 当绘制类型是多边形时
          // 实体不存在开始画多边形
          if (!isDrawPolyGon && !polyGonShow && defensLen < 3) {
            // 获取坐标信息
            let nowPosition = editPolyGonFunC.getLonOrLat(event.position)

            // 点数据保存
            pointArr.push([nowPosition.longitude, nowPosition.latitude, 0])
            // 当前点数据
            nowPoint = [nowPosition.longitude, nowPosition.latitude, 0]

            // 画点
            const point = editPolyGonFunC.drawPoint([
              nowPosition.longitude,
              nowPosition.latitude,
              0,
            ])
            pointAndLineEntity.pointEntityArr.push(point)

            // 开始画多边形
            isDrawLine = true
            // 画线
            const num = pointArr.length
            if (num > 1) {
              editPolyGonFunC.delDemoEntity(pointAndLineEntity.demoLineEntityArr)
              const line = editPolyGonFunC.drawLine('line_name', [
                ...pointArr[num - 2],
                ...pointArr[num - 1],
              ])
              pointAndLineEntity.lineEntityArr.push(line)
            }
          }
        }
      }
      //点击多边形上的编辑点
      if (pick && pick.id && pick.id.point && pick.id.name == 'polygon_point') {
        nowEditPoint = []
        nowEditPoint.push(pick)
        isDrawPolyGon = true
      }

      if (shapeType.value == 'circle') {
        //当绘制类型是圆形时
        if (defensLen < 3) {
          let lens = 0
          if (circleEntity.circlePonit.length > 0) {
            const newArr = circleEntity.circlePonit.filter((item, i, arr) => {
              return item.show == true
            })
            lens = newArr.length
          }
          if (lens == 0) {
            let nowPosition = editPolyGonFunC.getLonOrLat(event.position)
            // 当前点数据
            centerPoint = [nowPosition.longitude, nowPosition.latitude, 0]

            //绘制圆形，圆心，拖拽点
            editVisible.value = true
            drawCircles(centerPoint, circleRadius, 1)
          }
        }
      }
      //点击拖拽点
      if (pick && pick.id && pick.id._name == 'circle_drag') {
        if (dragCircle) {
          dragCircle = false
          selectCircleIndex = null
        } else {
          dragCircle = true
          circleEntity.circleDragPonit.map((item, index) => {
            if (pick.id._id == item._id) {
              selectCircleIndex = index
            }
          })
        }
      }
      //点击圆心
      if (pick && pick.id && pick.id._name == 'circle_center') {
        if (dragCircleCenter) {
          dragCircleCenter = false
          selectCircleIndex = null
        } else {
          dragCircleCenter = true
          circleEntity.circlePonit.map((item, index) => {
            if (pick.id._id == item._id) {
              selectCircleIndex = index
            }
          })
        }
      }
      //删除状态下，点击圆形，删除当前点击的圆
      if (pick && pick.id && pick.id._name == 'circle_name') {
        if (deleteShape.value) {
          deleteDenfenData()
          // circleEntity.circleEntityArr.map((item, index) => {
          //   if (pick.id._id == item._id) {
          //     viewer.entities.remove(item)
          //     circleEntity.circleEntityArr.splice(index, 1)
          //     circleEntity.circleDragPonit.splice(index, 1)
          //     circleEntity.circlePonit.splice(index, 1)
          //   }
          // })
          // defensArr.map((item, index) => {
          //   if (item.id == pick.id._id) {
          //     defensArr.splice(index, 1)
          //   }
          // })
        }
        if (editShape.value) {
          editVisible.value = true
          circleEntity.circleEntityArr.map((item, index) => {
            if (pick.id._id == item._id) {
              editPolyGonFunC.delDemoEntity(pointAndLineEntity.pointEntityArr) //隐藏多边形的编辑点
              circleEntity.circlePonit.map((item, num) => {
                if (num == index) {
                  item.show = true
                } else {
                  item.show = false
                }
              })
              circleEntity.circleDragPonit.map((item, num) => {
                if (num == index) {
                  item.show = true
                } else {
                  item.show = false
                }
              })
            }
          })
        }
      }
      if (clickIndex.value == 1 && drawType.value == 1 && shapeType.value == '') {
        message({
          message: '请先选择需要绘制的形状',
          type: 'warning',
        })
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    // 鼠标移动事件
    handler.setInputAction((event) => {
      //鼠标移动多边形编辑点
      if (isDrawLine && !isDrawPolyGon) {
        // 画框逻辑
        // 获取坐标信息
        let movePosition = editPolyGonFunC.getLonOrLat(event.startPosition)
        // 删除上一次生成
        editPolyGonFunC.delDemoEntity(pointAndLineEntity.demoLineEntityArr)
        // 创建线
        const demoLine = editPolyGonFunC.drawLine('line_demo_name', [
          ...nowPoint,
          ...[movePosition.longitude, movePosition.latitude, 0],
        ])
        pointAndLineEntity.demoLineEntityArr.push(demoLine)
      } else if (isDrawPolyGon && !isDrawLine) {
        // 编辑逻辑
        // 获取坐标信息
        let movePosition = editPolyGonFunC.getLonOrLat(event.startPosition)
        // 更新点坐标
        nowEditPoint[0].id.position = Cesium.Cartesian3.fromDegrees(
          movePosition.longitude,
          movePosition.latitude,
          0
        )
        // 获取更新面坐标的数据
        updatePoints = []
        pointAndLineEntity.pointEntityArr.forEach((item) => {
          updatePoints.push(item.position._value)
        })
        // 更新面坐标
        pointAndLineEntity.polygonEntityArr[0].id.polygon.hierarchy = updatePoints
      }

      //拖动圆心或者拖拽点
      if (dragCircleCenter || dragCircle) {
        //鼠标移动圆形圆心，拖拽点
        //移动拖拽点
        let data = circleEntity.circleEntityArr[selectCircleIndex]
        let nowRadius = 0
        if (dragCircle) {
          let movePosition = editPolyGonFunC.getLonOrLat(event.startPosition)
          // 更新拖拽点坐标
          let nowPosition = [Number(movePosition.longitude), Number(movePosition.latitude), 0]
          circleEntity.circleDragPonit[selectCircleIndex].position = Cesium.Cartesian3.fromDegrees(
            ...nowPosition
          )

          //更新圆半径
          nowRadius = editCircleFunC.getPointsDistance(centerPoint, nowPosition) //计算两点之前距离
          circleRadius = nowRadius
          circleEntity.circleEntityArr[selectCircleIndex].ellipse.semiMajorAxis = Number(nowRadius)
          circleEntity.circleEntityArr[selectCircleIndex].ellipse.semiMinorAxis = Number(nowRadius)
        }
        //移动圆心
        if (dragCircleCenter) {
          let movePosition = editPolyGonFunC.getLonOrLat(event.startPosition)
          //更新圆心
          circleEntity.circlePonit[selectCircleIndex].position = Cesium.Cartesian3.fromDegrees(
            movePosition.longitude,
            movePosition.latitude,
            0
          )
          centerPoint = [movePosition.longitude, movePosition.latitude, 0]
          //更新圆位置
          circleEntity.circleEntityArr[selectCircleIndex].position = Cesium.Cartesian3.fromDegrees(
            movePosition.longitude,
            movePosition.latitude,
            0
          )
          //更新拖拽点
          let dragPosition = editCircleFunC.getLonAndLat(
            movePosition.longitude,
            movePosition.latitude,
            90,
            circleRadius
          )
          circleEntity.circleDragPonit[selectCircleIndex].position = Cesium.Cartesian3.fromDegrees(
            dragPosition.lng,
            dragPosition.lat,
            0
          )
        }
        //更新defensArr的数据
        defensArr.map((item) => {
          if (item.id == data._id) {
            if (dragCircle) {
              item.radius = nowRadius
            }
            if (dragCircleCenter) {
              item.data = centerPoint
            }
            item.info = circleEntity.circleEntityArr[selectCircleIndex]
          }
        })
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

    // 鼠标右击事件
    handler.setInputAction((event) => {
      if (!isDrawPolyGon && isDrawLine) {
        // 结束画多边形
        isDrawLine = false
        // 删除鼠标移动画线
        editPolyGonFunC.delDemoEntity(pointAndLineEntity.demoLineEntityArr)
        // 封闭多边形
        // const num = pointArr.length
        // drawLine('line_name', [...pointArr[num - 1], ...pointArr[0]])
        // 画多边形结束,形成面开始
        let len = defensArr.length
        let randomId = generateRandomStr()
        let flyIndex = len == 0 ? 1 : len == 1 ? 5 : 10
        editVisible.value = true
        const polyGon = editPolyGonFunC.drawPolyGon(
          randomId,
          pointArr,
          defensColorMap.get(flyIndex),
          10 - flyIndex
        )
        pointAndLineEntity.addPolygonEntity.push(polyGon)
        let defensItem = {
          type: flyIndex,
          shapeType: 1,
          data: pointArr,
          id: randomId,
          info: polyGon,
        }
        defensArr.push(defensItem)
        // 清空数据
        // 删除画点以及画线
        editPolyGonFunC.delDemoEntity(pointAndLineEntity.lineEntityArr)
        editPolyGonFunC.delDemoEntity(pointAndLineEntity.pointEntityArr)
        pointArr = []
        nowPoint = []
      } else if (isDrawPolyGon && !isDrawLine) {
        //更新三级防御圈数据
        let data = pointAndLineEntity.polygonEntityArr[0]
        defensArr.map((item) => {
          if (item.id == data.id._id) {
            let nowPosition = []
            updatePoints.map((item) => {
              //世界坐标转GPS坐标（角度值）[经度，纬度，高度]
              var result = Cesium.Cartographic.fromCartesian(item)
              var arr = [
                (result.longitude * 180) / Math.PI,
                (result.latitude * 180) / Math.PI,
                result.height,
              ]
              nowPosition.push(arr)
            })
            item.data = nowPosition
          }
        })
        isDrawPolyGon = false
      }
      polyGonShow = true
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
  }
  /**
   * @description: 绘制圆形防御圈
   * @param {*} centerPoint 圆心坐标
   * @param {Number} circleRadius 半径
   * @param {Number} visible 是否显示圆心和拖拽点 1：显示 0：不显示
   */
  const drawCircles = (centerPoint, circleRadius, visible = 1, type) => {
    // 画圆心
    const point = editCircleFunC.drawPoint(centerPoint)
    point.show = visible
    circleEntity.circlePonit.push(point)

    //画圆
    let len = defensArr.length
    let randomId = generateRandomStr()
    let flyIndex = 0
    if (type) {
      flyIndex = type
    } else {
      flyIndex = len == 0 ? 1 : len == 1 ? 5 : 10
    }
    const circle = editCircleFunC.drawCircle(
      randomId,
      centerPoint,
      circleRadius,
      defensColorMap.get(flyIndex),
      10 - flyIndex
    )
    circleEntity.circleEntityArr.push(circle)
    let defensItem = {
      type: flyIndex,
      shapeType: 2,
      data: centerPoint,
      radius: circleRadius,
      id: randomId,
      info: circle,
    }
    defensArr.push(defensItem)

    //拖动圆形半径的点
    //getLonAndLat:根据圆心，半径，角度计算圆边缘的某个点坐标
    let dragPosition = editCircleFunC.getLonAndLat(centerPoint[0], centerPoint[1], 90, circleRadius)
    let dragPositionArr = [dragPosition.lng, dragPosition.lat, 0]
    const dragPoint = editCircleFunC.drawDragPoint(dragPositionArr)
    dragPoint.show = visible
    circleEntity.circleDragPonit.push(dragPoint)
  }
  /**
   * @description: 生成随机数
   */
  const generateRandomStr = () => {
    let randomStr = 'defenseNo' + Math.floor(Math.random() * 100000)
    return randomStr
  }

  /**
   * @description: 切换图层的方法
   */
  const changBaseMap = (layer) => {
    // viewer.imageryLayers.removeAll(true) // 移e除所有图层并销毁
    // 定义本地瓦片底图的URL
    var localTilesetUrl = `/mapApi/${layer}/Mapnik/{z}/{x}/{y}.png`
    // 创建ImageryProvider
    var localTileProvider = new Cesium.UrlTemplateImageryProvider({
      url: localTilesetUrl,
    })
    // 创建ImageryLayer并添加到Viewer中
    viewer.imageryLayers.addImageryProvider(localTileProvider)
  }
  /**
   * @description: 切换地图图层
   */
  const changeLayer = () => {
    if (vectorShow.value) {
      changBaseMap('haiNingSatellite')
    } else {
      changBaseMap('haiNingVector')
    }
    vectorShow.value = !vectorShow.value
  }
  /**
   * @description: 远程搜索地址
   */
  const remoteMethod = (query) => {
    if (query) {
      loading.value = true
      setTimeout(() => {
        loading.value = false
        options.value = list.value.filter((item) => {
          return item.label.toLowerCase().includes(query.toLowerCase())
        })
      }, 200)
    } else {
      options.value = []
    }
  }
  /**
   * @description: 点击绘制防御圈的相关按钮 2：编辑 3：删除 1：绘制
   */
  const clickBtn = (index) => {
    let defensLen = defensArr.length
    if (index == 2 || index == 3) {
      if (defensLen == 0) {
        message({
          message: '暂无防御圈数据，请先绘制',
          type: 'warning',
        })
      } else {
        if (index == 2) {
          editShape.value = true
          toolText.value =
          `1.鼠标左击选中需要编辑的防御圈；<br/>
          2.多边形：点击各编辑点移动鼠标进行修改，鼠标右击结束编辑；<br/>
          3.圆形：鼠标左击选中圆形或圆上的编辑点，移动鼠标进行修改，再次鼠标左击结束编辑。`
        } else {
          deleteShape.value = true
          toolText.value ="鼠标左击选中防御圈进行删除。"
        }
        clickIndex.value = index
      }
    }
    if (index == 1) {
      if (defensLen !== 3) {
        clickIndex.value = 1
        toolText.value =
          `1.请先选择绘制方式，手动绘制或自动绘制；<br />
          2.手动绘制时，请先选择绘制的形状；<br />
        绘制多边形：鼠标左击选点，右击结束绘制多边形；<br />绘制圆形：左击选中圆心画圆，默认半径为1000m,
        可鼠标左击选中圆上的拖拽点进行拖动，修改半径大小；
        <br />3.自动绘制时，请在输入框内输入半径值，回车进行绘制圆形，圆形圆心会默认以核心防御圈的中心为值；<br />
         4.绘制完成后，请点击退出绘制模式，返回上一级。`
      } else {
        message({
          message: '已存在防御圈，请进行编辑或删除操作',
          type: 'warning',
        })
      }
    }
  }
  /**
   * @description: 删除三级防御圈
   */
  const deleteDenfenData = () => {
    //删除多边形
    editPolyGonFunC.delDemoEntity(pointAndLineEntity.pointEntityArr)
    editPolyGonFunC.delDemoEntity(pointAndLineEntity.addPolygonEntity)
    //删除圆形
    editCircleFunC.delDemoEntity(circleEntity.circlePonit)
    editCircleFunC.delDemoEntity(circleEntity.circleEntityArr)
    editCircleFunC.delDemoEntity(circleEntity.circleDragPonit)
    //清空数组
    defensArr = []
  }
  /**
   * @description: 退出绘制/编辑/删除模式
   */
  const closeDraw = (index) => {
    if (index == 2) {
      editShape.value = false
      isDrawPolyGon = false
      polyGonShow = false
      // 删除多边形编辑的点
      editPolyGonFunC.delDemoEntity(pointAndLineEntity.pointEntityArr)
      //隐藏圆心和拖拽点
      circleVisible(false)
    } else if (index == 3) {
      deleteShape.value = false
    }
    clickIndex.value = 0
  }
  /**
   * @description: 选择绘制的方式 1：手动绘制，2：自动绘制
   */
  const onDrawType = (index) => {
    let defensLen = defensArr.length
    if (defensLen < 3) {
      drawType.value = index
      if (index == 2) {
        if (defensLen == 0) {
          drawType.value = 0
          message({
            message:
              '自动绘制是以第一次绘制图形的中心点为圆心，绘制圆形布防区,检测到地图数据为空,请先绘制一个图形',
            type: 'warning',
          })
        } else if (defensLen < 3) {
          shapeType.value = 'autoCircle'
        }
      }
    } else {
      message({
        message: '三级防御圈绘制完成，请先退出绘制模式',
        type: 'warning',
      })
    }
  }
  /**
   * @description: 选择绘制的形状 polygon：多边形，circle：圆形
   */
  const selectShape = (val) => {
    shapeType.value = val
    if (!val) {
      // 结束绘制
      clickIndex.value = 1
      drawType.value = 0
      //隐藏圆心和拖拽点
      circleVisible(false)
      autoDraw = false
      polyGonShow = false
    }
  }
  /**
   * @description: 隐藏/显示圆心和圆形拖拽点
   */
  const circleVisible = (val) => {
    if (circleEntity.circlePonit.length > 0) {
      circleEntity.circlePonit.map((item, index) => {
        item.show = val
      })
    }
    if (circleEntity.circleDragPonit.length > 0) {
      circleEntity.circleDragPonit.map((item, index) => {
        item.show = val
      })
    }
  }
  /**
   * @description: 自动绘制
   */
  let autoDraw = false
  const changeRadius = (val) => {
    var re = /^[0-9]+.?[0-9]*/ //判断字符串是否为数字//判断正整数/[1−9]+[0−9]∗]∗/
    if (!re.test(val)) {
      message({
        message: '请输入数字',
        type: 'warning',
      })
    } else {
      let firstDenfens = defensArr[0]
      let circleCenter = []
      if (firstDenfens.shapeType == 1) {
        //当核心圈是多边形时，获取多边形的中心
        circleCenter = getPolygonCenter(firstDenfens)
      } else {
        //当核心圈时圆形时，获取圆心
        circleCenter = [...firstDenfens.data]
      }
      if (!autoDraw) {
        drawCircles(circleCenter, Number(val), 0)
        autoDraw = true
      } else {
        let circleLen = circleEntity.circleEntityArr.length
        let dragLen = circleEntity.circleDragPonit.length
        //更新当前圆半径
        circleEntity.circleEntityArr[circleLen - 1].ellipse.semiMajorAxis = Number(val)
        circleEntity.circleEntityArr[circleLen - 1].ellipse.semiMinorAxis = Number(val)
        //更新拖拽点的位置
        let dragPosition = editCircleFunC.getLonAndLat(
          Number(circleCenter[0]),
          Number(circleCenter[1]),
          90,
          Number(val)
        )
        circleEntity.circleDragPonit[dragLen - 1].position = Cesium.Cartesian3.fromDegrees(
          dragPosition.lng,
          dragPosition.lat,
          0
        )
        //更新三级防御圈数据
        defensArr[defensArr.length - 1].radius = Number(val)
        defensArr[defensArr.length - 1].info = circleEntity.circleEntityArr[circleLen - 1]
      }
      radiusVal.value=''
    }
  }
  /**
   * @description: 获取多边形的中心点
   */
  const getPolygonCenter = (pick) => {
    //当核心圈是多边形时，获取多边形的中心
    var polyPositions = pick.info.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions
    var polyCenter = Cesium.BoundingSphere.fromPoints(polyPositions).center //中心点
    let cartographic = Cesium.Cartographic.fromCartesian(
      polyCenter,
      viewer.scene.globe.ellipsoid,
      new Cesium.Cartographic()
    )
    let lat = Cesium.Math.toDegrees(cartographic.latitude)
    let lng = Cesium.Math.toDegrees(cartographic.longitude)
    let circleCenter = [lng, lat, 0]
    return circleCenter
  }
  /**
   * @description: 新增编辑上传参数
   */
  const getParams = () => {
    let params = {
      managementBoundaryInfos: [],
    }
    defensArr.map((item) => {
      if (item.shapeType == 1) {
        //多边形
        let dataCenter = getPolygonCenter(item)
        let coordinateTDOS = []
        item.data.map((element) => {
          coordinateTDOS.push({
            longitude: element[0],
            latitude: element[1],
            gpsLongitude: element[0],
            gpsLatitude: element[1],
          })
        })
        params.managementBoundaryInfos.push({
          shape: 1,
          longitude: dataCenter[0],
          latitude: dataCenter[1],
          limitFlyType: item.type,
          managementCoordinateTDOS: coordinateTDOS,
        })
      } else if (item.shapeType == 2) {
        //圆形
        params.managementBoundaryInfos.push({
          shape: 0,
          limitFlyType: item.type,
          longitude: item.data[0],
          latitude: item.data[1],
          radius: item.radius,
        })
      }
    })
    return params
  }

  /**
   * @description: 确认三级防御圈
   */
  const editVisible = ref(false)
  const onConfirm = () => {
    let defensLength = defensInfos.value.length
    // 新增
    if (defensLength == 0) {
      if (defensArr.length !== 3) {
        message({
          message: '请先完成三级防御圈的绘制',
          type: 'warning',
        })
      } else {
        let params = getParams()
        createDefense(params).then((res) => {
          if (res.code * 1 == 200) {
            message({
              message: '添加成功',
              type: 'success',
            })
            closePopu();
          } else {
            message({
              message: res.msg,
              type: 'error',
            })
          }
        })
      }
    } else {
      if (defensArr.length == 3) {
        //编辑
        if (editVisible.value) {
          let params = getParams()
          params.id = defensId.value
          editDefense(params).then((res) => {
            if (res.code * 1 == 200) {
              message({
                message: '修改成功',
                type: 'success',
              })
              closePopu();
            } else {
              message({
                message: res.msg,
                type: 'error',
              })
            }
          })
        } else {
          message({
            message: '请先进行编辑或删除操作',
            type: 'warning',
          })
        }
      } else if (defensArr.length == 0) {
        //删除
        let params = { id: defensId.value, status: -1 }
        delDefense(params).then((res) => {
          if (res.code * 1 == 200) {
            message({
              message: '删除成功',
              type: 'success',
            })
            closePopu();
          } else {
            message({
              message: res.msg,
              type: 'error',
            })
          }
        })
      } else {
        message({
          message: '请先完成三级防御圈的绘制！',
          type: 'warning',
        })
      }
    }
  }
  const closePopu=()=>{
    //更新驾驶舱的三级防御圈
    setTimeout(() => {
      close()
      emit('getDenfensInfo')
    }, 500)
  }

  /**
   * @description: 回显三级防御圈
   */
  const defensInfos = ref([]) //三级防御圈数据
  const defensId = ref(null) //当前三级圈ID
  const mapCenter = ref([])
  const getDenfensInfo = () => {
    getDefense().then((res) => {
      if (res.code * 1 == 200) {
        defensInfos.value = res.data
        if (res.data.length > 0) {
          defensId.value = res.data[0].id
          let infos = res.data[0].managementBoundaryInfos
          infos.map((item, index) => {
            let randomId = generateRandomStr()
            let pointArr = []
            item.managementCoordinateTDOS.map((tdos) => {
              pointArr.push([Number(tdos.longitude), Number(tdos.latitude), 0])
            })
            if (item.shape == 1) {
              const polyGon = editPolyGonFunC.drawPolyGon(
                randomId,
                pointArr,
                defensColorMap.get(item.limitFlyType),
                9 - index
              )
              pointAndLineEntity.addPolygonEntity.push(polyGon)
              let defensItem = {
                type: item.limitFlyType,
                shapeType: 1,
                data: pointArr,
                id: randomId,
                info: polyGon,
              }
              defensArr.push(defensItem)
            } else if (item.shape == 0) {
              //绘制圆形，圆心，拖拽点
              mapCenter.value = [Number(item.longitude), Number(item.latitude)]
              centerPoint = [Number(item.longitude), Number(item.latitude), 0]
              drawCircles(centerPoint, Number(item.radius), 0, item.limitFlyType)
            }
          })
        }
      }
      defaultAngle()
    })
  }
  /**
   * @description: 默认视角
   */
  const defaultAngle = () => {
    if (mapCenter.value.length > 0) {
      viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(mapCenter.value[0], mapCenter.value[1], 24000), // 定位点
        orientation: {
          heading: Cesium.Math.toRadians(0.0), // 方向（从正北开始）
          pitch: Cesium.Math.toRadians(-90.0), // 倾斜度（向下）
          roll: 0.0, // 滚动度
        },
      })
    } else {
      /* 设置相机位置-海宁 */
      viewer.camera.setView({
        // 设置相机位置
        destination: {
          x: -2816848.42615148,
          y: 4743740.974434502,
          z: 3230577.710770937,
        },
        orientation: {
          // 初始视角
          heading: 6.28119452736122,
          pitch: -1.5707956694526715,
          roll: 0,
        },
      })
    }
  }
  onMounted(() => {
    initMap()
    getDenfensInfo()
    emit('enableTool', false)
  })
</script>

<style scoped lang="scss">
  :deep(.el-select__wrapper) {
    border: 1px solid #408fd6;
    box-shadow: none;
    background-color: #ffffff !important;
    min-height: 30px !important;
  }
  .content {
    padding-top: 10px;
    .flex-content {
      display: flex;
      margin-bottom: 20px;
      .flex-title {
        width: 100px;
        font-weight: 400;
        font-size: 16px;
        line-height: 30px;
        color: #ffffff;
      }
      .select-eqiupment {
        display: flex;
        height: 30px;
        align-items: center;
        .select-item {
          height: 30px;
          line-height: 30px;
          background: #e8f4ff;
          border-radius: 5px;
          border: 1px solid #d1e9ff;
          text-align: center;
          font-size: 12px;
          color: #2f9cff;
          padding: 0 10px;
          margin-right: 10px;
          .close-icon {
            font-size: 15px;
            padding-left: 5px;
            vertical-align: middle;
            font-weight: bolder;
          }
        }
      }
      .map-edit {
        width: 927px;
        // height: 435px;
        background-color: #ffffff;
        .btn-list {
          width: 100%;
          height: 48px;
          padding: 0 20px;
          box-sizing: border-box;
          display: flex;
          justify-content: space-between;
          align-items: center;
          .draw-title {
            color: red;
            font-size: 14px;
            padding-right: 15px;
          }
        }
        #coverageMap {
          width: 100%;
          height: 450px;
        }
      }
    }
    .btn-box {
      width: 100%;
      height: 31px;
    }
    .content-btn {
      width: 89px;
      height: 31px;
      background: linear-gradient(90deg, #21a4d7 0%, #1550ab 100%);
      border: 1px solid #80ebfd;
      box-shadow: inset 0 0 10px rgba(255, 255, 255, 0.7);
      color: #ffffff;
      line-height: 31px;
      text-align: center;
      margin-bottom: 20px;
      float: right;
      cursor: pointer;
    }
  }
  .radius-txt {
    font-size: 14px;
  }
  .radius-input {
    :deep(.el-input__inner) {
      color: #606266;
    }
  }
</style>
